#include "stm32f10x.h"
#include "Delay.h"


static uint8_t  us = 0;
static uint16_t ms = 0;

void Delay_Init(uint8_t MHz)	//72MHz
{
	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);	//8分频，72M/8=9M
	us = MHz/8;					//1us计数9个
	ms = (uint16_t)us*1000;		//1ms计数9000个
}

/*
2的24次方 = 3个2的8次方 = 256*256*256 = 16777216	(24位递减计数器计数个数)
16777216/9000 = 1864.135	(能计时1864ms，最多计时1.864s)
注意最大定时时间为1.864s
*/

/**
  * @brief  毫秒级延时
  * @param  xms 延时时长，参数最大写1864
  * @retval 无
  */
void Delay_ms(uint32_t xms)
{
	uint32_t temp;
	SysTick ->LOAD = (uint32_t)ms*xms;	//重载值
	SysTick ->VAL  = 0;
	SysTick ->CTRL |= SysTick_CTRL_ENABLE_Msk;//软件方式开启计数器，使能
	//开启计数器另一种写法	SysTick ->CTRL = 0x01;
	do{
		temp = SysTick ->CTRL;
	}while( (temp & 0x01) && !(temp & (1<<16)) );	//COUNTFLAG = 1，就代表计数完毕
	//(temp & 0x01)	检查计数器是否开启

	SysTick ->VAL  = 0;
	SysTick ->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
	//关闭计数器另一种写法	SysTick ->CTRL = 0x00;
}


/**
  * @brief  微秒级延时
  * @param  ums 延时时长
  * @retval 无
  */
void Delay_us(uint32_t xus)
{
	uint32_t temp;
	SysTick ->LOAD = us*xus;
	SysTick ->VAL  = 0;
	SysTick ->CTRL |= SysTick_CTRL_ENABLE_Msk;
	do{
		temp = SysTick ->CTRL;
	}while( (temp & 0x01) && !(temp & (1<<16)) );

	SysTick ->VAL  = 0;
	SysTick ->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}

void Delay_s(uint32_t xs)
{
	while(xs--)
	{
		Delay_ms(1000);
	}
} 



/*jiangkeda*/
///**
//* @brief  微秒级延时
//* @param  xus 延时时长，范围：0~233015
//* @retval 无
//*/
//void Delay_us(uint32_t xus)
//{
//SysTick->LOAD = 72 * xus;				//设置定时器重装值
//SysTick->VAL = 0x00;					//清空当前计数值
//SysTick->CTRL = 0x00000005;				//设置时钟源为HCLK，启动定时器
//while(!(SysTick->CTRL & 0x00010000));	//等待计数到0
//SysTick->CTRL = 0x00000004;				//关闭定时器
//}

///**
//* @brief  毫秒级延时
//* @param  xms 延时时长，范围：0~4294967295
//* @retval 无
//*/
//void Delay_ms(uint32_t xms)
//{
//while(xms--)
//{
//	Delay_us(1000);
//}
//}

///**
//* @brief  秒级延时
//* @param  xs 延时时长，范围：0~4294967295
//* @retval 无
//*/
//void Delay_s(uint32_t xs)
//{
//while(xs--)
//{
//	Delay_ms(1000);
//}
//} 


